import cors from "cors";
import morgan from "morgan";
import express, { Request, Response } from "express";
import { init as initDB, authenticate } from "./db";
import entities from "./entity";

const logger = morgan("tiny");

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);

Object.entries(entities).forEach(([key, _handler]) => {
  const [type, name] = key.split(" ");
  const handler = async (req: Request, res: Response) => {
    await authenticate();
    await _handler(req, res);
  };
  switch (type) {
    case "GET":
    default:
      app.get(name, handler);
      break;
    case "POST":
      app.post(name, handler);
      break;
    case "PUT":
      app.put(name, handler);
      break;
    case "DELETE":
      app.delete(name, handler);
      break;
  }
});

const port = process.env.PORT || 3002;

async function bootstrap() {
  await initDB();
  app.listen(port, () => {
    console.log("启动成功", port);
  });
}

bootstrap();
